package javassist;

import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class Test1<test1> {
    public static void main(String[] args) throws Exception {

        testField();


        User user = new User(); user.setName("大罗");
        System.out.println(JSONObject.toJSONString(user));
    }

    public static void testObject() throws CannotCompileException, NotFoundException {
        ClassPool pool = ClassPool.getDefault();
        CtClass ctClass = pool.get("javassist.User");
        CtMethod m = CtNewMethod.make("public Knife getKnife(){return new javassist.Knife();}", ctClass);
        ctClass.addMethod(m);
        Class clazz = ctClass.toClass();
        System.out.println(clazz);
    }


    public static void testInteger() throws CannotCompileException, NotFoundException {
        ClassPool pool = ClassPool.getDefault();
        CtClass ctClass = pool.get("javassist.User");
        CtMethod m = CtNewMethod.make("public Integer getAge(){return 1;}", ctClass);
        ctClass.addMethod(m);
        Class clazz = ctClass.toClass();
        System.out.println(clazz);
    }

    public static void testString() throws CannotCompileException, NotFoundException {
        ClassPool pool = ClassPool.getDefault();
        CtClass ctClass = pool.get("javassist.User");
        CtMethod m = CtNewMethod.make("public String getAlias(){return \"大头\";}", ctClass);
        ctClass.addMethod(m);
        Class clazz = ctClass.toClass();
        System.out.println(clazz);
    }


    public static void testField() throws CannotCompileException, NotFoundException, NoSuchFieldException, IllegalAccessException {
        ClassPool pool = ClassPool.getDefault();
        CtClass ctClass = pool.get("javassist.User");
        CtClass ctClassString = pool.get("java.lang.String");
        CtField f = new CtField(ctClassString, "introduce", ctClass); //没有String类型
        f.setModifiers(Modifier.PUBLIC);
//        CtMethod m = CtNewMethod.make("public Integer getIntroduce(){return introduce;}", ctClass);
        ctClass.addField(f);
//        ctClass.addMethod(m);
        Class clazz = ctClass.toClass();
        System.out.println(clazz);

        Field field  = clazz.getField("introduce");

        User user = new User(); user.setName("大罗");

        field.set(user, "中国青年");
        System.out.println(JSONObject.toJSONString(user));
    }

}
